package com.ticket.web.controller.yanchu;

import com.ticket.common.annotation.Log;
import com.ticket.common.constant.PerformConstants;
import com.ticket.common.core.controller.BaseController;
import com.ticket.common.core.domain.AjaxResult;
import com.ticket.common.core.page.TableDataInfo;
import com.ticket.common.enums.BusinessType;
import com.ticket.common.utils.DateUtils;
import com.ticket.common.utils.JsoupUtils;
import com.ticket.common.utils.NumberReplaceUtils;
import com.ticket.common.utils.StringUtils;
import com.ticket.common.utils.poi.ExcelUtil;
import com.ticket.system.domain.YanchuSeat;
import com.ticket.system.domain.YanchuSession;
import com.ticket.system.domain.vo.SeatImportVo;
import com.ticket.system.domain.vo.SeatVo;
import com.ticket.system.service.IYanchuSeatService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.w3c.dom.Document;
import org.xhtmlrenderer.swing.Java2DRenderer;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 场次座位Controller
 * 
 * @date 2023-09-26
 */
@Api(description = "座位管理")
@RestController
@RequestMapping("/system/seat")
public class YanchuSeatController extends BaseController
{
    @Autowired
    private IYanchuSeatService yanchuSeatService;
    @Value("${notifyUrl}")
    private String notifyUrl;

    /**
     * 查询场次座位列表
     */
    @PreAuthorize("@ss.hasPermi('system:seat:list')")
    @GetMapping("/list")
    public TableDataInfo list(YanchuSeat yanchuSeat)
    {
        startPage();
        List<YanchuSeat> list = yanchuSeatService.selectYanchuSeatList(yanchuSeat);
        return getDataTable(list);
    }

    /**
     * 开票管理座位列表
     */
    @ApiOperation("开票管理座位列表")
    @ApiImplicitParam(name = "sessionId", value = "场次编码1：已放票，2：占有票等待支付，3：已支付，4：不外放 5已验票 6已取消", dataType = "Long", dataTypeClass = Long.class)
    @GetMapping("/listTicket")
    public TableDataInfo<SeatVo> listTicket(@RequestParam Long sessionId)
    {
        List<SeatVo> list = yanchuSeatService.selectSeatVoList(sessionId);
        return getDataTable(list);
    }

    /**
     * 导出场次座位列表
     */
    @ApiOperation("导出场次座位列表")
    @ApiImplicitParam(name = "sessionId", value = "场次编码1：已放票，2：占有票等待支付，3：已支付，4：不外放 5已验票 6已取消", dataType = "Long", dataTypeClass = Long.class)
    @PreAuthorize("@ss.hasPermi('system:seat:export')")
    @Log(title = "场次座位", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, @RequestParam Long sessionId)
    {
        YanchuSession session = yanchuSeatService.selectSessionVo(sessionId);
        List<SeatVo> list = yanchuSeatService.selectSeatVoExportList(sessionId);
        if(!CollectionUtils.isEmpty(list)){
            for(SeatVo seatVo:list){
                if(StringUtils.isNotEmpty(seatVo.getIdType())){
                    if (StringUtils.isNotEmpty(seatVo.getIdNum()) && seatVo.getIdType().equals("身份证")) {
                        //身份证
                        seatVo.setIdNum(NumberReplaceUtils.idCardAddStar(seatVo.getIdNum()));
                    } else if (StringUtils.isNotEmpty(seatVo.getIdNum()) && seatVo.getIdType().equals("护照")) {
                        //护照
                        seatVo.setIdNum(NumberReplaceUtils.passportAddStar(seatVo.getIdNum()));
                    }
                }

                if(session.getAutType().equals(PerformConstants.AUTH_NONE)){
                    //seatVo.setIdNum(null);
//                    seatVo.setBuyer(null);
//                    seatVo.setBuyerPhone(null);
                }
                if(seatVo.getShowNumber().indexOf("桌")>0){
                    seatVo.setRowNumberStr(seatVo.getShowNumber().substring(0,seatVo.getShowNumber().indexOf("桌")+1));
                }else if(seatVo.getShowNumber().indexOf("厢")>0){
                    seatVo.setRowNumberStr(seatVo.getShowNumber().substring(0,seatVo.getShowNumber().indexOf("厢")+1));
                }
//                if(StringUtils.isNotEmpty(seatVo.getBuyerPhone())){
//                    seatVo.setBuyerPhone(StringUtils.maskPhone(seatVo.getBuyerPhone()));
//                }
//                if(StringUtils.isNotEmpty(seatVo.getIdNum())){
//                    seatVo.setIdNum(StringUtils.maskIdNum(seatVo.getIdNum()));
//                }
            }
        }
        ExcelUtil<SeatVo> util = new ExcelUtil<SeatVo>(SeatVo.class);
        util.exportExcel(response, list, "场次座位数据",session.getPerformName()+"\n场次："+session.getSessionName()+"\n导出时间："+ DateUtils.dateTimeNow("yyyy-MM-dd HH:mm"));
    }

    /**
     * 获取场次座位详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:seat:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(yanchuSeatService.selectYanchuSeatById(id));
    }

    /**
     * 新增场次座位
     */
    @PreAuthorize("@ss.hasPermi('system:seat:add')")
    @Log(title = "场次座位", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody YanchuSeat yanchuSeat)
    {
        return toAjax(yanchuSeatService.insertYanchuSeat(yanchuSeat));
    }

//    @ApiOperation("抢座")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "sessionId", value = "场次编码", dataType = "Integer", dataTypeClass = Integer.class),
//            @ApiImplicitParam(name = "seatVos", value = "座位", dataType = "SeatVo", dataTypeClass = SeatVo.class)
//    })
//    @Log(title = "抢座", businessType = BusinessType.OTHER)
//    @PostMapping("/grabTicket")
//    public AjaxResult grabTicket(HttpServletRequest request,
//                                 Integer sessionId,
//                                 @RequestBody List<SeatVo> seatVos)
//    {
//        TWxUser wxUser = WxUserThreadLocal.get();
//        return yanchuSeatService.grabTicket(sessionId,wxUser.getUserId(),seatVos);
//    }

    /**
     * 修改场次座位
     */
    @PreAuthorize("@ss.hasPermi('system:seat:edit')")
    @Log(title = "场次座位", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody YanchuSeat yanchuSeat)
    {
        return toAjax(yanchuSeatService.updateYanchuSeat(yanchuSeat));
    }

    /**
     * 删除场次座位
     */
    @PreAuthorize("@ss.hasPermi('system:seat:remove')")
    @Log(title = "场次座位", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(yanchuSeatService.deleteYanchuSeatByIds(ids));
    }

    @ApiOperation("座位导出")
    @Log(title = "座位导出", businessType = BusinessType.EXPORT)
    @PostMapping("/exportSeatData")
    @ApiImplicitParam(name = "seatImportVos", value = "导入座位", dataType = "SeatImportVo", dataTypeClass = SeatImportVo.class)
    public void exportSeatData(@RequestBody List<SeatImportVo> seatImportVos,HttpServletResponse response)
    {
        yanchuSeatService.executeExportOrder(seatImportVos, response);
    }

    @ApiOperation("座位导入")
    @ApiImplicitParam(name = "file", value = "导入文件", dataType = "MultipartFile", dataTypeClass = MultipartFile.class)
    @Log(title = "座位导入", businessType = BusinessType.IMPORT)
    @PostMapping("/importSeatData")
    public AjaxResult<SeatImportVo> importSeatData(MultipartFile file) throws Exception
    {
        List<SeatImportVo> userList = yanchuSeatService.executeImportOrder(file);
        return success(userList);
    }

    @ApiOperation("行列表")
    @ApiImplicitParam(name = "idArea", value = "区域编码", dataType = "Long", dataTypeClass = Long.class)
    @GetMapping(value = "/rowList")
    public List<YanchuSeat> rowList(Long idArea){
        return yanchuSeatService.selectRowListByAreaId(idArea);
    }

    @ApiOperation("座位列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "idArea", value = "区域编码", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "rowNumber", value = "行号", dataType = "Long", dataTypeClass = Long.class)
    })
    @GetMapping(value = "/seatList")
    public List<YanchuSeat> seatList(Long rowNumber,Long idArea){
        return yanchuSeatService.selectSeatListByRowNo(rowNumber,idArea);
    }

    /** <p>通过Java2DRenderer将html转为图片</p>
     * <ol>
     *     <li>通过jsoup根据url获取静态html</li>
     *     <li>使用Java2DRenderer将静态html转为图片，浏览器下载</li>
     * </ol>
     */
    @ApiOperation("通过Java2DRenderer将html转为图片")
    @GetMapping("/htmlToImage")
    public void htmlToImage(HttpServletResponse response){
        String url = "http://www.baidu.com";
        String fileName = "座位图.png";
        Document document = null;
        ServletOutputStream out = null;
        try {
            String html = JsoupUtils.getHtmlByJsoup(url);
            logger.info("html:{}",html);
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            document = builder.parse(new ByteArrayInputStream(html.getBytes()));
            Java2DRenderer renderer = new Java2DRenderer(document, 480, 640);
            BufferedImage img = renderer.getImage();
            response.setCharacterEncoding(StandardCharsets.UTF_8.name());
            response.setContentType("image/png;charset=".concat(StandardCharsets.UTF_8.name()));
            response.setHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS,HttpHeaders.CONTENT_DISPOSITION);
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
                    "attachment; filename=".concat(
                            URLEncoder.encode(fileName, StandardCharsets.UTF_8.name())
                    ));
            out = response.getOutputStream();
            //把 BufferedImage 缓冲图像流 写到 输出流 out 中
            ImageIO.write(img, "png", out);
        }catch(Exception e){
            logger.error("htmlToImage error",e);
            throw new RuntimeException("转换图片失败");
        }finally {
            if(null != out){
                try {
                    out.close();
                }catch (Exception e){
                    logger.error("转换图片失败",e);
                }
            }
        }
    }
}
